package com.alan.springBoot.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.alan.springBoot.exception.BusinessException;
import com.alan.springBoot.mapper.UserMapper;
import com.alan.springBoot.model.User;

@RestController
@RequestMapping("test")
public class TestController {

	Logger logger = Logger.getLogger(TestController.class);
	
	@Autowired
	private UserMapper userMapper;
	
	@GetMapping("hello")
	public ModelAndView hello() {
		ModelAndView mav = new ModelAndView();
		mav.addObject( "name", "7777" );
		mav.setViewName( "hello" );
		return mav;
	}
	
	@RequestMapping("hello2")
	public ModelAndView hello2() {
		ModelAndView mav = new ModelAndView();
		ModelMap modelMap = mav.getModelMap();
		modelMap.put( "name", "789797" );
		return mav;
	}
	
	@RequestMapping("hello3")
	@ResponseBody//这还是返回一个视图
	public ModelAndView hello3() {
		String tt ="aa";
		Integer.valueOf(tt);
		ModelAndView mav = new ModelAndView();
		ModelMap modelMap = mav.getModelMap();
		modelMap.put( "name", "789444797" );
		return mav;
	}
	
	@RequestMapping("json")
	@ResponseBody//这还是返回一个视图
	public ModelAndView json() {
		ModelAndView mav = new ModelAndView();
		ModelMap modelMap = mav.getModelMap();
		modelMap.put( "name", "789444797" );
		String tt ="aa";
		try {
			Integer.valueOf(tt);
		} catch (Exception e) {
			throw new BusinessException("TEST",e);
		}
		return mav;
	}
	
	@RequestMapping("json2")//返回的是json
	public ModelAndView json2() {
		ModelAndView mav = new ModelAndView();
		//ModelMap modelMap = mav.getModelMap();
		//modelMap.put( "name", "789444797" );
		MappingJackson2JsonView mjsv = new MappingJackson2JsonView();
		Map attributes = new HashMap();
		attributes.put("success", Boolean.TRUE);
		attributes.put("contractNo", "contractNo");
		mjsv.setAttributesMap( attributes );
		/*String tt ="aa";
		try {
			Integer.valueOf(tt);
		} catch (Exception e) {
			throw new BusinessException("TEST",e);
		}*/
		mav.setView( mjsv );
		return mav;
	}
	
	@RequestMapping("hello1")
	public String hello1() {
		return "hello";
	}
	
	@RequestMapping("user")
	public List<User> user() {
		List<User> list = userMapper.selectByExample(null);
		logger.info("test-user="+list.size());
		return list;
	}

	@RequestMapping(value = "test", method = RequestMethod.POST)
	public String test(@RequestBody Object js){
//        System.out.println(js.toJSONString());
//        Vtest vtest = JSON.toJavaObject(js,Vtest.class);
//        System.out.println(JSON.toJSONString(vtest));
		return JSON.toJSONString(js);
	}

}
